package lesson2.example4;

import java.lang.reflect.Method;
import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {

	private static Logger logger = LogManager.getLogger(LogAspect.class);

	// 切点
	@Pointcut("@annotation(lesson2.example4.LogAnnotation)")
	public void logPointCut() {

	}

	// 环绕增强
	@Around("logPointCut()")
	public Object around(ProceedingJoinPoint point) throws Throwable {
		long beginTime = System.currentTimeMillis();
		Object result = point.proceed();
		long time = System.currentTimeMillis() - beginTime;
		log(point, time);
		return result;
	}

	private void log(ProceedingJoinPoint joinPoint, long time) {
		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();

		StringBuilder sb = new StringBuilder();
		LogAnnotation syslog = method.getAnnotation(LogAnnotation.class);
		if (syslog != null) {
			sb.append(syslog.logType());
			sb.append(" ");
			sb.append(syslog.value());
		}

		String className = joinPoint.getTarget().getClass().getName();
		String methodName = signature.getName();
		sb.append(className + "." + methodName + "()");

		sb.append(time);
		sb.append(new Date());
		
		
		logger.info(sb.toString());
	}
}